import html2canvas from "html2canvas"
import JsPDF from "jspdf"
const SIZE = [595.28, 841.89]

function getScrollWidth() {
  var noScroll, scroll
  var oDiv = document.createElement('DIV')
  oDiv.style.cssText = 'position:absolute; top:-1000px; width:100px; height:100px; overflow:hidden;'
  noScroll = document.body.appendChild(oDiv).clientWidth
  oDiv.style.overflowY = 'scroll'
  scroll = oDiv.clientWidth
  document.body.removeChild(oDiv)
  return noScroll - scroll
}

export default {
  savePDFSingle(doc) {
    console.log('doc', doc)
    let node = doc
    let nodeW
    if (getScrollWidth()) {
      nodeW = node.clientWidth - (17 - getScrollWidth())
    } else {
      nodeW = node.clientWidth
    }
    let pageH = nodeW / SIZE[0] * SIZE[1]

    let modules = node.children
    for (let i = 0, len = modules.length; i < len; i++) {
      let item = modules[i]
      let beforeH = item.offsetTop
      let afterH = beforeH + item.clientHeight
      let currentPage = parseInt(beforeH / pageH)
      /* if (currentPage !== parseInt(afterH / pageH)) {
        let lastItemAftarH = modules[i].offsetTop + modules[i].clientHeight
        let fill = pageH - lastItemAftarH % pageH
        item.style.marginTop = fill + 'px'
      } */
    }
    return html2canvas(node, {
      useCORS: true,
      scale: 2,
      height: node.scrollHeight,
      windowHeight: node.scrollHeight,
      scrollY: -window.scrollY
    })
  },
  async savePDF(nodes, title) {
    return Promise.all([
      ...nodes.map(v => this.savePDFSingle(v))
    ]).then(function (canvases) {
      let PDF = new JsPDF('', 'pt', 'a4')

      canvases.forEach((canvas, canvasIndex) => {
        let contentWidth = canvas.width
        let contentHeight = canvas.height
        let pageHeight = contentWidth / SIZE[0] * SIZE[1]
        let leftHeight = contentHeight
        let position = 20
        let sidesway = 38
        let imgWidth = SIZE[0] - sidesway * 2
        let imgHeight = imgWidth / contentWidth * contentHeight
        let pageData = canvas.toDataURL('image/jpeg', 1.0)
        if (leftHeight < pageHeight) {
          PDF.addImage(pageData, 'JPEG', sidesway, position, imgWidth, imgHeight)

        } else {
          while (leftHeight > 0) {
            PDF.addImage(pageData, 'JPEG', sidesway, position, imgWidth, imgHeight)
            leftHeight -= pageHeight
            position -= SIZE[1]
            if (leftHeight > 0) {
              PDF.addPage()
            }
          }
        }

        if (canvasIndex !== canvases.length - 1) {
          PDF.addPage()

        }
      })
      return PDF.save(title + '.pdf')
    })
  }

}
